<?php
use think\Db;
use taobao\AliSms;

function qlkey($api_id,$record,$money,$key){
    $data = [
       'api_id' => $api_id,//商户ID
       'record' => $record,//附加参数
       'money' => sprintf("%.2f",$money)//金额
   ];
    
    ksort($data);
    $str1 = '';
    foreach ($data as $k => $v) {//组装参数
      $str1 .= '&' . $k . "=" . $v;
    }
    
   return md5(trim($str1) . $key);//md5加密参数
}

//鸡sir加密方法
function makeSign($arr, $cert)
{
    $arr = array_filter($arr, function ($val) {
        return ($val === '' || $val === null) ? false : true;
    });
    if (isset($arr['sign'])) {
        unset($arr['sign']);
    }
    ksort($arr);
    $str = http_build_query($arr);
    $old_str = urldecode($str) . '&cert=' . $cert;
    $str = md5($old_str);
    return  strtoupper($str);
}

/**
 * 产生随机字符串
 *
 * @param    int        $length  输出长度
 * @param    string     $chars   可选的 ，默认为 0123456789
 * @return   string     字符串
 */
function get_random($length, $chars = '0123456789') {
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

// curl 请求
if (!function_exists('curlRequest')) {
    function curlRequest($url, $data = [], $headers = [], $timeout = 10, $method = 'GET')
    {
        $curl = curl_init();
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
 
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
 
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
 
        if (!empty($data) && 'GET' == $method) $method = 'POST';
 
        switch ($method) {
            case 'POST':
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
            case 'PUT':
                curl_setopt($curl, CURLOPT_PUT, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
            case 'DELETE':
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
        }
 
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
 
        if (curl_errno($curl)) {
            echo 'Curl error: ' . curl_error($curl);exit;
        }
        curl_close($curl);
 
        return $output;
    }
}

function aes128Encrypt($key, $data) {

    $padding = 16 - (strlen($data) % 16);

    $data=str_pad($data,strlen($data) + 16 - strlen($data) % 16,chr($padding));

    $keySize   = 16;

    $ivSize    = 16;

    $rawKey = $key;

    $genKeyData = '';

    do

    {

        $genKeyData = $genKeyData.md5( $genKeyData.$rawKey,true);

    } while(

            strlen( $genKeyData ) < 32

    );

    $generatedKey = substr($genKeyData, 0, $keySize );

    $generatedIV  = substr($genKeyData, 16, 16);

    return openssl_encrypt($data,'aes-128-cbc', $generatedKey, OPENSSL_NO_PADDING, $generatedIV);

}

//模拟http
function get_cur($url, $data="", $type="GET", $header="")
{
    $HTTP_REFERER='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_REFERER, $HTTP_REFERER);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    if (!empty($data)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if (!empty($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    curl_close($ch);
    return $temp;
}

function getSign(array $data, $appSecret)
{
    ksort($data);
    $need = [];
    foreach ($data as $key => $value) {
        if (! $value || $key == 'sign') {
            continue;
        }
        $need[] = "{$key}={$value}";
    }
    $string = implode('&', $need).$appSecret;

    return strtoupper(md5($string));
}


function laoyanggetSign($secret, $data) {

        // 去空
        $data = array_filter($data);

        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a = http_build_query($data);

        $string_a = urldecode($string_a);

        //签名步骤二：在string后加入mch_key
        $string_sign_temp = $string_a . "&key=" . $secret;

        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);

        // 签名步骤四：所有字符转为大写
        $result = strtoupper($sign);

        return $result;
}


function laoyangverifySign($data, $key) {
        // 验证参数中是否有签名
        if (!isset($data['sign']) || !$data['sign']) {
            $this->error = '没传签名字符串';
            return false;
        }

        // 要验证的签名串
        $sign = $data['sign'];
        unset($data['sign']);
        $secret = $key;
        // 生成新的签名、验证传过来的签名
        $sign2 = laoyanggetSign($secret, $data);
        if ($sign != $sign2) {
            $this->error = '签名错误';
            return false;
        }
        return true;
}


function markSignH5($paydata,$signkey){
    ksort ( $paydata );
	$str = '';
	foreach ( $paydata as $k => $v ) {
		if ($k != "sign" && $v != "") {
			$str .= $k . "=" . $v . "&";
		}
	}
	return strtoupper ( md5 ( $str . "key=" . $signkey ) );
}


function taoqimaomk($arr, $cert)
    {
        $arr = array_filter($arr);
        if (isset($arr['sign'])) {
            unset($arr['sign']);
        } 
        ksort($arr);
        $str = http_build_query($arr);
        $str = urldecode($str).'&cert='.$cert;
        $str = md5($str);
        return  strtoupper($str);
    }
    /** 把网络图片图片转成base64
     * @param string $img 图片地址
     * @return string
     */
    /*网络图片转为base64编码*/
    // function imgtobase64($img='', $imgHtmlCode=true)
    // {
    //     $imageInfo = getimagesize($img);
    //     $base64 = "" . chunk_split(base64_encode(file_get_contents($img)));
    //     return 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img)));
    // }

function httpPost($url, $paramStr){
	$curl = curl_init();
	curl_setopt_array($curl, array(
	  CURLOPT_URL => $url,
	  CURLOPT_RETURNTRANSFER => 1,
	  CURLOPT_TIMEOUT => 30,
	  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	  CURLOPT_CUSTOMREQUEST => "POST",
	  CURLOPT_POSTFIELDS => $paramStr,
	  CURLOPT_HTTPHEADER => array(
		"cache-control: no-cache",
		"content-type: application/x-www-form-urlencoded"
	  ),
	));
	$response = curl_exec($curl);
	$err = curl_error($curl);
	curl_close($curl);
	if ($err) {
	  return $err;
	}
	return $response;
}


function geturldata($url) 
{ 
    $ch = curl_init(); 
    curl_setopt ($ch, CURLOPT_URL, $url); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10); 
    $content = curl_exec($ch); 
    curl_close($ch);
    // if(empty($content)){
    //     $content = geturldatas($url);
    // }
   
    return $content; 
}

function geturldatas($url) 
{ 
    $ch = curl_init(); 
    curl_setopt ($ch, CURLOPT_URL, $url); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10); 
    $content = curl_exec($ch); 
    curl_close($ch);
    if(empty($content)){
        $content = geturldata($url);
    }
    return $content; 
}

function newposturl($url, $data)
{
    
    
    $data = json_encode($data);
   
    $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
 
    curl_close($curl);
    return json_decode($output, true);
}


	
function paramArraySign($paramArray, $mchKey){
	
	ksort($paramArray);  //字典排序
	reset($paramArray);

	$md5str = "";
	foreach ($paramArray as $key => $val) {
		if( strlen($key)  && strlen($val) ){
			$md5str = $md5str . $key . "=" . $val . "&";
		}
	}
	$sign = strtoupper(md5($md5str . "key=" . $mchKey));  //签名
	
	return $sign;
	
}

/**
 * 字符串截取，支持中文和其他编码
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    if (function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif (function_exists('iconv_substr'))
    {
        $slice = iconv_substr($str, $start, $length, $charset);
        if (false === $slice)
        {
            $slice = '';
        }
    }
    else
    {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice . '...' : $slice;
}

    function get_rand($proArr) { 
 $result = ''; 
 //概率数组的总概率精度 
 $proSum = array_sum($proArr); 
 //概率数组循环 
 foreach ($proArr as $key => $proCur) { 
  $randNum = mt_rand(1, $proSum); 
  if ($randNum <= $proCur) { 
   $result = $key; 
   break; 
  } else { 
   $proSum -= $proCur; 
  }  
 } 
 unset ($proArr); 
 return $result; 
} 


function get_pwd_strength($pwd){
        if (strlen($pwd)>16 || strlen($pwd)<6)
        {
            return "密码必须为6-30位的字符串";
        }
        if(preg_match("/^\d*$/",$pwd))
        {
            return "密码必须包含字母,强度:弱";//全数字
        }
        if(preg_match("/^[a-z]*$/i",$pwd))
        {
            return "密码必须包含数字,强度:中";//全字母
        }
        if(!preg_match("/^[a-z\d]*$/i",$pwd))
        {
            return "密码只能包含数字和字母,强度:强";//有数字有字母 ";
        }
        return true;
    }



    //翻译入口
function translate($query, $from, $to)
{
    $args = array(
        'q' => $query,
        'appid' => "20201215000648267",
        'salt' => rand(10000,99999),
        'from' => $from,
        'to' => $to,

    );
    $args['sign'] = buildSign($query, "20201215000648267", $args['salt'], "hqnvXCxZ8471vUYtL9v9");
    $ret = call("http://api.fanyi.baidu.com/api/trans/vip/translate", $args);
    $ret = json_decode($ret, true);
    return $ret; 
}

//加密
function buildSign($query, $appID, $salt, $secKey)
{
    $str = $appID . $query . $salt . $secKey;
    $ret = md5($str);
    return $ret;
}


function call($url, $args=null, $method="post", $testflag = 0, $timeout = 10, $headers=array())
{/*{{{*/
    $ret = false;
    $i = 0; 
    while($ret === false) 
    {
        if($i > 1)
            break;
        if($i > 0) 
        {
            sleep(1);
        }
        $ret = callOnce($url, $args, $method, false, $timeout, $headers);
        $i++;
    }
    return $ret;
}

function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = 10, $headers=array())
{
    $ch = curl_init();
    if($method == "post") 
    {
        $data = convert($args);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    else 
    {
        $data = convert($args);
        if($data) 
        {
            if(stripos($url, "?") > 0) 
            {
                $url .= "&$data";
            }
            else 
            {
                $url .= "?$data";
            }
        }
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(!empty($headers)) 
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    if($withCookie)
    {
        curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
    }
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

function convert(&$args)
{
    $data = '';
    if (is_array($args))
    {
        foreach ($args as $key=>$val)
        {
            if (is_array($val))
            {
                foreach ($val as $k=>$v)
                {
                    $data .= $key.'['.$k.']='.rawurlencode($v).'&';
                }
            }
            else
            {
                $data .="$key=".rawurlencode($val)."&";
            }
        }
        return trim($data, "&");
    }
    return $args;
}


/**
 * 除去数组中的空值和签名参数
 * @param $para 签名参数组
 * return 去掉空值与签名参数后的新签名参数组
 */
function paraFilter($para) {
	$para_filter = array();
	foreach ($para as $key=>$val) {
		if($key == "sign" || $key == "sign_type" || $val == "")continue;
		else $para_filter[$key] = $para[$key];
	}
	return $para_filter;
}
/**
 * 对数组排序
 * @param $para 排序前的数组
 * return 排序后的数组
 */
function argSort($para) {
	ksort($para);
	reset($para);
	return $para;
}

/**
 * 签名字符串
 * @param $prestr 需要签名的字符串
 * @param $key 私钥
 * return 签名结果
 */
function md5Sign($prestr, $key) {
	$prestr = $prestr . $key;
	return md5($prestr);
}

/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstring($para) {
	$arg  = "";
	foreach ($para as $key=>$val) {
		$arg.=$key."=".$val."&";
	}
	//去掉最后一个&字符
	$arg = substr($arg,0,-1);
	
	return $arg;
}


function get_week_arr(){
 
    //获取今天是周几，0为周日
    $this_week_num = date('w');
 
    $timestamp = time();
    //如果获取到的日期是周日，需要把时间戳换成上一周的时间戳
    //英语国家 一周的开始时间是周日
    if($this_week_num == 0){
        $timestamp = $timestamp - 86400;
    }
 
    $this_week_arr =  [
        [
            'week_time'=>strtotime(date('Y-m-d', strtotime("this week Monday", $timestamp))),
        ],
        [
            'week_time'=>strtotime(date('Y-m-d', strtotime("this week Tuesday", $timestamp))),
        ],
        [
            'week_time'=>strtotime(date('Y-m-d', strtotime("this week Wednesday", $timestamp))),
        ],
        [
            'week_time'=>strtotime(date('Y-m-d', strtotime("this week Thursday", $timestamp))),
        ],
        [
            'week_time'=>strtotime(date('Y-m-d', strtotime("this week Friday", $timestamp))),
        ],
        [
            'week_time'=>strtotime(date('Y-m-d', strtotime("this week Saturday", $timestamp))),
        ],
        [
            'week_time'=>strtotime(date('Y-m-d', strtotime("this week Sunday", $timestamp))),
        ],
    ];
 
    return $this_week_arr;
}

function http_post($sUrl, $aHeader, $aData) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $sUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($aData));
    $sResult = curl_exec($ch);
    if ($sError = curl_error($ch)) {
        die($sError);
    }
    curl_close($ch);
    return $sResult;
}


function saomacurl($url, $post_data) {
	$ch = curl_init ();
	$header = [
			'Content-Type: application/json',
			'Content-Length: ' . strlen ( $post_data )
	];
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	// 我们在POST数据哦！
	curl_setopt ( $ch, CURLOPT_POST, 1 );
	// 把post的变量加上
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
	
	$output = curl_exec ( $ch );
	curl_close ( $ch );
    
	return $output;
}



/**
 * 签名方法
 */
function saomamarkSign($paydata, $signkey) {
   
    ksort ( $paydata );
    $str = '';
    foreach ( $paydata as $k => $v ) {
        if ($k != "sign" && $v != "") {
            $str .= $k . "=" . $v . "&";
        }
    }
    return strtoupper ( md5 ( $str . "key=" . $signkey ) );
}



function check_ts($ip = '',$uopenid = '',$openid = ''){
    
    $ts = 0;
    
    if(!empty($ip)){
         $cunzai  = Db::name("ts")->where(['ip' => $ip,'type' => 1])->find();
         if(!empty($cunzai)){
            $ts = 1;
         }
    }
   
    
    if(!empty($uopenid)){
         $cunzai2 = Db::name("ts")->where(['uopenid ' => $uopenid,'type' => 1])->find();
         if(!empty($cunzai2)){
              $ts = 1;
         }
    }
    
    if(!empty($openid)){
         $cunzai3 = Db::name("ts")->where(['openid ' => $openid,'type' => 1])->find();
         if(!empty($cunzai3)){
              $ts = 1;
         }
    }
  
    return $ts;
 
}

function is_weixin(){
     $user_agent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($user_agent, 'MicroMessenger') == false && strpos($user_agent, 'Windows Phone') == false) {
        $wx_mobile = false;
    } else {
        $wx_mobile = true;
    }
    
     return $wx_mobile;
}

function alert_url($t0) {
	die('<script type="text/javascript">window.location.href="'.$t0.'"</script>');
}

  //curl发起post请求
    function posturl($url, $data)
    {
        $data = json_encode($data);
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);

        return json_decode($output, true);
    }
    
    
    //支付方法内使用，客户不需要调用！
function posturlhuang($url, $data)
{
    $data = json_encode($data);
    $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HTTPHEADER,array(
        'Content-Type: application/json',
    ));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return json_decode($output, true);
}



function wx_mobile(){
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $mobile_agents = Array("240x320", "acer", "acoon", "acs-", "abacho", "ahong", "airness", "alcatel", "amoi", "android", "anywhereyougo.com", "applewebkit/525", "applewebkit/532", "asus", "audio", "au-mic", "avantogo", "becker", "benq", "bilbo", "bird", "blackberry", "blazer", "bleu", "cdm-", "compal", "coolpad", "danger", "dbtel", "dopod", "elaine", "eric", "etouch", "fly ", "fly_", "fly-", "go.web", "goodaccess", "gradiente", "grundig", "haier", "hedy", "hitachi", "htc", "huawei", "hutchison", "inno", "ipad", "ipaq", "ipod", "jbrowser", "kddi", "kgt", "kwc", "lenovo", "lg ", "lg2", "lg3", "lg4", "lg5", "lg7", "lg8", "lg9", "lg-", "lge-", "lge9", "longcos", "maemo", "mercator", "meridian", "micromax", "midp", "mini", "mitsu", "mmm", "mmp", "mobi", "mot-", "moto", "nec-", "netfront", "newgen", "nexian", "nf-browser", "nintendo", "nitro", "nokia", "nook", "novarra", "obigo", "palm", "panasonic", "pantech", "philips", "phone", "pg-", "playstation", "pocket", "pt-", "qc-", "qtek", "rover", "sagem", "sama", "samu", "sanyo", "samsung", "sch-", "scooter", "sec-", "sendo", "sgh-", "sharp", "siemens", "sie-", "softbank", "sony", "spice", "sprint", "spv", "symbian", "tablet", "talkabout", "tcl-", "teleca", "telit", "tianyu", "tim-", "toshiba", "tsm", "up.browser", "utec", "utstar", "verykool", "virgin", "vk-", "voda", "voxtel", "vx", "wap", "wellco", "wig browser", "wii", "windows ce", "wireless", "xda", "xde", "zte");
    $is_mobile = false;

    $wx_mobile = false;
    foreach ($mobile_agents as $device) // 这里把值遍历一遍，用于查找是否有上述字符串出现过
    {
        if (stristr($user_agent, $device)) // stristr 查找访客端信息是否在上述数组中，不存在即为PC端。
        {
            $is_mobile = true;
            break;
        }
    }

   
    if (strpos($user_agent, 'MicroMessenger') == false && strpos($user_agent, 'Windows Phone') == false) {
        $wx_mobile = false;
    } else {
        $wx_mobile = true;
    }

    if($wx_mobile  && $is_mobile){

          return true;

    }else{
          return false;
    }


}







function get_duan_url($url = '',$param=''){
    
     if (empty($url) || empty($param))
    {
        return false;
    }

    $postUrl  = $url;
    $curlPost = $param;
    
    $ch = curl_init($url); //请求的URL地址
    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);//$data JSON类型字符串
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($param)));
    $data = curl_exec($ch); //运行curl
    curl_close($ch);
    
    
    return $data;
    
}

/**
 * 调用系统的API接口方法（静态方法）
 * api('User/getName','id=5'); 调用公共模块的User接口的getName方法
 * api('Admin/User/getName','id=5');  调用Admin模块的User接口
 * 
 * @param string $name 格式 [模块名]/接口名/方法名
 * @param array $ |string  $vars 参数
 */
function api($name, $vars = array())
{
    $array = explode('/', $name);
    $method = array_pop($array);
    $classname = array_pop($array);
    $module = $array? array_pop($array) : 'common';
    $callback = 'app\\' . $module . '\\Api\\' . $classname . 'Api::' . $method;
    if (is_string($vars))
    {
        parse_str($vars, $vars);
    }
    return call_user_func_array($callback, $vars);
}

/**
 * 获取配置的分组
 * 
 * @param string $group 配置分组
 * @return string 
 */
function get_config_group($group = 0)
{
    $list = config('config_group_list');
    return $group?$list[$group]:'';
}

/**
 * 获取配置的类型
 * 
 * @param string $type 配置类型
 * @return string 
 */
function get_config_type($type = 0)
{
    $list = config('config_type_list');
    return $list[$type];
}

/**
 * 发送短信(参数：签名,模板（数组）,模板ID，手机号)
 */
function sms($signname = '', $param = [], $code = '', $phone)
{
    $alisms = new AliSms();
    $result = $alisms->sign($signname)->data($param)->code($code)->send($phone);
    return $result['info'];
}

/**
 * 循环删除目录和文件
 * 
 * @param string $dir_name 
 * @return bool 
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if (is_dir($dir_name))
    {
        if ($handle = opendir($dir_name))
        {
            while (false !== ($item = readdir($handle)))
            {
                if ($item != '.' && $item != '..')
                {
                    if (is_dir($dir_name . DS . $item))
                    {
                        delete_dir_file($dir_name . DS . $item);
                    }
                    else
                    {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name))
            {
                $result = true;
            }
        }
    }

    return $result;
}
// 时间格式化1
function formatTime($time)
{
    $now_time = time();
    $t = $now_time - $time;
    $mon = (int) ($t / (86400 * 30));
    if ($mon >= 1)
    {
        return '一个月前';
    }
    $day = (int) ($t / 86400);
    if ($day >= 1)
    {
        return $day . '天前';
    }
    $h = (int) ($t / 3600);
    if ($h >= 1)
    {
        return $h . '小时前';
    }
    $min = (int) ($t / 60);
    if ($min >= 1)
    {
        return $min . '分钟前';
    }
    return '刚刚';
}
// 时间格式化2
function pincheTime($time)
{
    $today = strtotime(date('Y-m-d')); //今天零点
    $here = (int)(($time - $today) / 86400) ;
    if ($here == 1)
    {
        return '明天';
    }
    if ($here == 2)
    {
        return '后天';
    }
    if ($here >= 3 && $here < 7)
    {
        return $here . '天后';
    }
    if ($here >= 7 && $here < 30)
    {
        return '一周后';
    }
    if ($here >= 30 && $here < 365)
    {
        return '一个月后';
    }
    if ($here >= 365)
    {
        $r = (int)($here / 365) . '年后';
        return $r;
    }
    return '今天';
}

function dwz($url, $type)
{
    $url2 = '';

    switch ($type)
    {
        case 1:
            $html = file_get_contents("http://980.so/api.php?format=json&url=" . $url);
            $result = json_decode($html, true);

            $url2 = $result['url'];
            break;
        case 2:
            $html = file_get_contents("http://suo.im/api.php?format=json&url=" . $url);
            $result = json_decode($html, true);
            $url2 = $result['url'];
            break;

        case 3:
            $html = file_get_contents("http://ff.ttylxqf.bar/index.php/index/api/add?&username=yuzhou&key=mxXDBHuRl9Syf2J&url=" . $url);
            $result = json_decode(trim($html, chr(239) . chr(187) . chr(191)), true);
            $url2 = $result['url'];
            break;

        case 4:
            $html = file_get_contents("http://api.kks.me/api.php?format=json&url=" . $url);
            $result = json_decode(trim($html, chr(239) . chr(187) . chr(191)), true);
            $url2 = $result['url'];
            break;

        case 5:
            $html = file_get_contents("http://api.rrd.me/api.php?format=json&url=" . $url);
            $result = json_decode(trim($html, chr(239) . chr(187) . chr(191)), true);
            $url2 = $result['url'];
            break;

        case 6:
            $html = file_get_contents("http://api.uee.me/api.php?format=json&url=" . $url);
            $result = json_decode(trim($html, chr(239) . chr(187) . chr(191)), true);
            $url2 = $result['url'];
            break;

        case 7:
            $url2 = file_get_contents("http://6du.in/?is_api=1&lurl=" . $url);
            break;

        case 8:
            $html = file_get_contents("http://mrw.so/api.php?format=json&url=" . $url);
            $result = json_decode(trim($html, chr(239) . chr(187) . chr(191)), true);
            $url2 = $result['url'];
            break;

        case 9:
            $html = file_get_contents("http://api.u6.gg/api.php?url=" . $url);
            $result = substr($html, 9);
            $url2 = $result;
            break;

        case 10:
            $url2 = file_get_contents("http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=" . $url);
            $json = json_decode($url2);
            $url2 = $json[0]->url_short;
            break;

        case 11:
            $url2 = file_get_contents("http://tools.aeink.com/tools/dwz/urldwz.php?api=urlcn&longurl=http://safetyurl.biaonong.shop/url.php?url=http://safety.dongshai.shop/Safeurl.php?url=" . $url);
            $json = json_decode($url2, true);
            $url2 = $json['ae_url'];
            break;

        case 12:
            $url2 = file_get_contents("http://yy.gongju.at/?a=addon&m=wxdwz&token=557971b67b4a1803b782789aee204ee0&long=" . $url);
            $json = json_decode($url2, true);
            $url2 = $json['short'];
            break;

        case 22:
            
              $token = "df4fdb6c8cc4afc123c4c1f813c6c754";//申请地址 http://baofeng.la
           	  $url2  = file_get_contents("http://yy.gongju.at/?a=addon&m=wxdwz2&token={$token}&long=".$url);
        	  $json  = json_decode($url2,true);
        // 	  return $json['short'];
        //     //$url2 = file_get_contents("http://8r.pw/api/weibourl.php?key=70checkkey&url=" . $url);
        //     $url2 = file_get_contents("https://api.uouin.com/index.php/index/Jiance/add?username=3458017194&key=dIlN25Kt2Tkr3w8&type=tcn&url=" . $url);
        //     $json = json_decode($url2, true);
            $url2 = $json['short'];
       
            break;

        case 23:
            //http://api.ft12.com/api.php?format=json&url=http%3a%2f%2fwww.baidu.com&apikey=yourkey
            //$url2 = file_get_contents("http://8r.pw/api/weibourl.php?key=70checkkey&url=" . $url);
            $url2 = file_get_contents("http://api.ft12.com/api.php?format=json&url=".$url."&apikey=KjCGkheJ3xeciAQTQs@ddd");
            $json = json_decode($url2, true);
            $url2 = $json['url'];
        break;

        default:
            $url2 = urldecode($url);
            break;
    }
    return $url2;
}






function lock_url($txt,$key='xiaodeng'){
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-="; 
    $nh = rand(0,63); 
    $ch = $chars[$nh]; 
    $mdKey = md5($key.$ch); 
    $mdKey = substr($mdKey,$nh%8, $nh%8+7); 
    $txt = base64_encode($txt); 
    $tmp = ''; 
    $i=0;$j=0;$k = 0; 
    for ($i=0; $i<strlen($txt); $i++) { 
        $k = $k == strlen($mdKey) ? 0 : $k; 
        $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%63; 
        $tmp .= $chars[$j]; 
    } 
    return urlencode($ch.$tmp); 
} 
//解密函数 
function unlock_url($txt,$key='xiaodeng'){ 
    $txt = urldecode($txt); 
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-="; 
    $ch = $txt[0]; 
    $nh = strpos($chars,$ch); 
    $mdKey = md5($key.$ch); 
    $mdKey = substr($mdKey,$nh%8, $nh%8+7); 
    $txt = substr($txt,1); 
    $tmp = ''; 
    $i=0;$j=0; $k = 0; 
    for ($i=0; $i<strlen($txt); $i++) { 
        $k = $k == strlen($mdKey) ? 0 : $k; 
        $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]); 
        while ($j<0) $j+=63; 
        $tmp .= $chars[$j]; 
    } 
    return base64_decode($tmp); 
} 


function random($length = 6, $type = 'string', $convert = 0)
{
    $config = array('number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );

    if (!isset($config[$type])) $type = 'string';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++)
    {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (!empty($convert))
    {
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}

function is_mobile()
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $mobile_agents = Array("240x320", "acer", "acoon", "acs-", "abacho", "ahong", "airness", "alcatel", "amoi", "android", "anywhereyougo.com", "applewebkit/525", "applewebkit/532", "asus", "audio", "au-mic", "avantogo", "becker", "benq", "bilbo", "bird", "blackberry", "blazer", "bleu", "cdm-", "compal", "coolpad", "danger", "dbtel", "dopod", "elaine", "eric", "etouch", "fly ", "fly_", "fly-", "go.web", "goodaccess", "gradiente", "grundig", "haier", "hedy", "hitachi", "htc", "huawei", "hutchison", "inno", "ipad", "ipaq", "ipod", "jbrowser", "kddi", "kgt", "kwc", "lenovo", "lg ", "lg2", "lg3", "lg4", "lg5", "lg7", "lg8", "lg9", "lg-", "lge-", "lge9", "longcos", "maemo", "mercator", "meridian", "micromax", "midp", "mini", "mitsu", "mmm", "mmp", "mobi", "mot-", "moto", "nec-", "netfront", "newgen", "nexian", "nf-browser", "nintendo", "nitro", "nokia", "nook", "novarra", "obigo", "palm", "panasonic", "pantech", "philips", "phone", "pg-", "playstation", "pocket", "pt-", "qc-", "qtek", "rover", "sagem", "sama", "samu", "sanyo", "samsung", "sch-", "scooter", "sec-", "sendo", "sgh-", "sharp", "siemens", "sie-", "softbank", "sony", "spice", "sprint", "spv", "symbian", "tablet", "talkabout", "tcl-", "teleca", "telit", "tianyu", "tim-", "toshiba", "tsm", "up.browser", "utec", "utstar", "verykool", "virgin", "vk-", "voda", "voxtel", "vx", "wap", "wellco", "wig browser", "wii", "windows ce", "wireless", "xda", "xde", "zte");
    $is_mobile = false;
    foreach ($mobile_agents as $device) // 这里把值遍历一遍，用于查找是否有上述字符串出现过
    {
        if (stristr($user_agent, $device)) // stristr 查找访客端信息是否在上述数组中，不存在即为PC端。
        {
            $is_mobile = true;
            break;
        }
    }
    return $is_mobile;
}

function writefile($fname, $str)
{
    $fp = fopen($fname, "w");
    fputs($fp, $str);
    fclose($fp);
}

function randColor()
{
    $colors = array();
    for ($i = 0; $i < 6; $i++)
    {
        $colors[] = dechex(rand(0, 15));
    }
    return implode('', $colors);
}

function is_HTTPS() // 判断是不是https
{
    if (!isset($_SERVER['HTTPS'])) return FALSE;
    if ($_SERVER['HTTPS'] === 1) // Apache
    {
        return TRUE;
    }elseif ($_SERVER['HTTPS'] === 'on') // IIS
    {
        return TRUE;
    }elseif ($_SERVER['SERVER_PORT'] == 443) // 其他
    {
        return TRUE;
    }
    return FALSE;
}

function get_ip_info($ip = '')
{
    $res = @file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip);
    if (empty($res))
    {
        return false;
    }

    $json = json_decode($res, true);

    return $json;
}

function getcurl($url = '', $param = '')
{
    if (empty($url) || empty($param))
    {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init(); //初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch); //运行curl
    curl_close($ch);

    return $data;
}

function getIP()
{
    static $realip;
    if (isset($_SERVER))
    {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
        {
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        }
        else
        {
            if (isset($_SERVER["HTTP_CLIENT_IP"]))
            {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            }
            else
            {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        }
    }
    else
    {
        if (getenv("HTTP_X_FORWARDED_FOR"))
        {
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        }
        else
        {
            if (getenv("HTTP_CLIENT_IP"))
            {
                $realip = getenv("HTTP_CLIENT_IP");
            }
            else
            {
                $realip = getenv("REMOTE_ADDR");
            }
        }
    }
    return $realip;
}


function getHttpContent($url, $method = 'GET', $postData = array()) {
    $data = '';
    $user_agent = $_SERVER ['HTTP_USER_AGENT'];
    $header = array(
        "User-Agent: $user_agent"
    );
    if (!empty($url)) {
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30); //30秒超时
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            //curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
            if (strstr($url, 'https://')) {
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            }

            if (strtoupper($method) == 'POST') {
                $curlPost = is_array($postData) ? http_build_query($postData) : $postData;
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
            }
            $data = curl_exec($ch);
            curl_close($ch);
        } catch (Exception $e) {
            $data = '';
        }
    }
    return $data;
}

function getClientIP($type = 0, $adv = false) {
    global $ip;
    $type = $type ? 1 : 0;
    if ($ip !== NULL)
        return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos]);
            $ip = trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array(
        $ip,
        $long) : array(
        '0.0.0.0',
        0);
    return $ip[$type];
}
























